<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Http\Requests\Shop\CategoryStore;
use App\Models\Shop\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index(Request $request)
   {
      $where = function ($query) use ($request) {
         if ($request->has('keyword') and $request->keyword != '') {
            $cate = $request->cate;
            $search = "%" . $request->keyword . "%";
            $query->where($cate, 'like', $search);
         }
      };

      $categories = Category::all_categories($where);

      return response()->json($categories);
   }


   /**
    * Store a newly created resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @return \Illuminate\Http\Response
    */
   public function store(CategoryStore $request)
   {
      $category = Category::create($request->all());
      if ($category) {
         $info = ['status' => 1, 'msg' => '新增分类成功~'];
         return response()->json($info);
      }
   }

   /**
    * Display the specified resource.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function show($id)
   {
      $category = Category::find($id);
      return response()->json($category);
   }


   /**
    * Update the specified resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function update(Request $request, $id)
   {
      $category = Category::find($id);
      $category->update($request->all());
   }

   /**
    * Remove the specified resource from storage.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function destroy($id)
   {
      $category = Category::with('children')->find($id);

      $info = ['status' => 1, 'msg' => '删除分类成功~'];
      //判断分类下是否有二级分类
      if (!$category->children->isEmpty()) {
         $info = ['status' => 0, 'msg' => '此分类下有二级分类，不能删除~'];
      }
      //判断分类下是否有商品
      $product = Category::check_products($id);
      if (!$product) {
         $info = ['status' => 0, 'msg' => '此分类下有商品，不能删除~'];
      }

      if ($info['status'] == 1) {
         Category::destroy($id);
      }

      return response()->json($info);
   }

   /***
    *  改变属性
    */
   public function change_attr(Request $request)
   {
      $category = Category::find($request->id);
      $category->is_show = !$request->is_show;
      $category->save();
   }

   /***
    *  排序
    */
   public function change_sort(Request $request)
   {
      $category = Category::find($request->id);
      $category->sort_order = $request->sort_order;
      $category->save();
   }
}
